<template>
  <div class="table">
    <el-table
      border
      ref="table"
      v-loading="loading"
      element-loading-text="加载中..."
      :data="tableData"
      :stripe="stripe"
      :max-height="tableHeight"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-bind="$attrs"
      @current-change="clickChange"
    >
      <slot name="select"></slot>
      <el-table-column v-if="props.singleSelect" align="center" type="index" width="40px">
        <template #default="scope">
          <el-radio
            class="table_single"
            :disabled="radioDisabledIds.includes(scope.row[props.rowId])"
            v-model="tableRadio"
            :label="scope.row[props.rowId]"
          ></el-radio>
        </template>
      </el-table-column>

      <el-table-column
        :fixed="props.fixed"
        v-if="props.serial"
        type="index"
        :label="props.serialLabel"
        :width="props.serialLabel === '序号' ? 60 : 120"
        :index="indexMethod"
      >
      </el-table-column>
      <slot></slot>
    </el-table>
    <div class="batchBtn">
      <slot name="batchBtn"></slot>
      <template v-if="props.select">
        <el-button @click="handleDisable(1)">
          {{ props.isWxGroup ? '启动服务' : '启用' }}
        </el-button>
        <el-button @click="handleDisable(2)">
          {{ props.isWxGroup ? '停止服务' : '停用' }}
        </el-button>
        <template v-if="props.isWxGroup">
          <el-button @click="handleKeyWord(0)"> 开启自动回复 </el-button>
          <el-button @click="handleKeyWord(1)"> 关闭自动回复 </el-button>
        </template>
      </template>
    </div>
    <div class="batchBtn" v-if="props.down">
      <el-button @click="handleDownLoad()">
        <el-icon>
          <Bottom></Bottom>
        </el-icon>
        导出
      </el-button>
    </div>
    <Pages v-if="props.page" :small="props.size === 'small'" v-model:page="page" :getTableData="getTableData"></Pages>
  </div>
</template>
<script setup lang="ts">
import store from '@/store';
import Pages from '@/components/Pages.vue';
import { findNode, findChildrenIds } from '@/hooks/findNodes.js';
const props = defineProps({
  //定义表格需要接收的值
  getTableDataFn: {
    type: Function,
  },
  searchForm: {
    type: Object,
  },
  searchParams: {
    type: Object,
  },
  stripe: {
    type: Boolean,
    default: true,
  },
  border: {
    type: Boolean,
    default: true,
  },
  serial: {
    type: Boolean,
    default: false,
  },
  page: {
    type: Boolean,
    default: true,
  },
  serialLabel: {
    type: String,
    default: '序号',
  },
  select: {
    type: Boolean,
    default: false,
  },
  down: {
    type: Boolean,
    default: false,
  },
  handleDisable: {
    type: Function,
  },
  handleKeyWord: {
    type: Function,
  },
  size: {
    type: String,
  },
  downLoad: {
    type: Function,
  },
  isWxGroup: {
    type: Boolean,
    default: false,
  },
  tableName: {
    type: String,
  },
  fixed: {
    type: Boolean,
    default: false,
  },
  maxHeight: {
    type: String,
  },
  singleSelect: {
    type: Boolean,
    default: false,
  },
  currentRow: {
    type: Object,
    default: {},
  },
  selectRow: {
    type: Object,
    default: {},
  },
  rowId: {
    type: String,
  },
});
const table = ref(null);

const loading = ref(false);
const tableData = ref([]);
const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const radioDisabledIds = ref([]);
const emits = defineEmits(['update:currentRow']);
const tableRadio = ref(null);
// 选中方法
const clickChange = (item: any) => {
  if (props.singleSelect && JSON.stringify(item) !== '{}' && !radioDisabledIds.value.includes(item[props.rowId])) {
    tableRadio.value = item[props.rowId];
    emits('update:currentRow', item);
  }
};
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const tableHeight = computed(() => {
  return props.maxHeight || store.getters.tableHeight;
});
const indexMethod = (index: number) => {
  return index + 1 + (page.currentPage - 1) * page.pageSize;
};
const qureyData = ref({});
const getTableData = async (searchParams = props.searchParams) => {
  qureyData.value = { ...searchParams };
  loading.value = true;
  try {
    const { data } = await props.getTableDataFn({
      data: { ...searchParams },
      pageSize: page.pageSize,
      pageNumber: page.currentPage,
    });
    tableData.value = data.content;
    page.total = data.total * 1;
    if (props.singleSelect && JSON.stringify(props.currentRow) !== '{}') {
      const row = findNode(tableData.value, props.rowId, props.currentRow[props.rowId]);
      nextTick(() => {
        if (row) table.value.setCurrentRow(row);
      });
    }
    if (props.singleSelect && JSON.stringify(props.selectRow) !== '{}') {
      const row = findNode(tableData.value, props.rowId, props.selectRow[props.rowId]);
      if (row) radioDisabledIds.value = findChildrenIds(row, props.rowId);
    }
  } catch (error) {
    tableData.value = [];
  }
  loading.value = false;
};
const handleSearch = (data) => {
  page.currentPage = 1;
  getTableData(data);
};
const handleDownLoad = () => {
  props
    .downLoad({
      data: { ...qureyData.value },
    })
    .then((res) => {
      var blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', props.tableName + '.xls');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};
onMounted(() => {
  getTableData();
});
onBeforeUnmount(() => {});
const handleDisable = (e) => {
  console.log(ElMessage);

  if (multipleSelection.value.length == 0) {
    ElMessage({
      message: '请至少选择一条数据',
      type: 'warning',
    });
    return;
  }
  props.handleDisable(e, multipleSelection.value);
};
const handleKeyWord = (e) => {
  if (multipleSelection.value.length == 0) {
    ElMessage({
      message: '请至少选择一条数据',
      type: 'warning',
    });
    return;
  }
  props.handleKeyWord(e, multipleSelection.value);
};
defineExpose({ handleSearch, handleDownLoad, tableData, multipleSelection });

// function ElMessage(arg0: { message: string; type: string }) {
//   throw new Error('Function not implemented.')
// }
</script>
<style lang="scss" scoped>
.table_single {
  :deep(.el-radio__label) {
    display: none;
  }
}
</style>
